package com.bocloud.cmp.service.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.CloudServerDao;
import com.bocloud.cmp.dao.FlavorDao;
import com.bocloud.cmp.dao.HostSystemDao;
import com.bocloud.cmp.dao.ImageDao;
import com.bocloud.cmp.dao.NetworkDao;
import com.bocloud.cmp.dao.PortDao;
import com.bocloud.cmp.dao.RegionDao;
import com.bocloud.cmp.dao.RouteDao;
import com.bocloud.cmp.dao.ServerDao;
import com.bocloud.cmp.dao.ServerIpDao;
import com.bocloud.cmp.dao.SnapshotDao;
import com.bocloud.cmp.dao.SubnetDao;
import com.bocloud.cmp.dao.VolumeDao;
import com.bocloud.cmp.entity.resource.CloudServer;
import com.bocloud.cmp.entity.resource.Flavor;
import com.bocloud.cmp.entity.resource.HostSystem;
import com.bocloud.cmp.entity.resource.Image;
import com.bocloud.cmp.entity.resource.Network;
import com.bocloud.cmp.entity.resource.Port;
import com.bocloud.cmp.entity.resource.Region;
import com.bocloud.cmp.entity.resource.Route;
import com.bocloud.cmp.entity.resource.Server;
import com.bocloud.cmp.entity.resource.ServerIp;
import com.bocloud.cmp.entity.resource.Snapshot;
import com.bocloud.cmp.entity.resource.Subnet;
import com.bocloud.cmp.entity.resource.Volume;
import com.bocloud.cmp.enums.VMStatus;
import com.bocloud.cmp.model.FlavorBean;
import com.bocloud.cmp.model.FlavorModel;
import com.bocloud.cmp.model.HostModel;
import com.bocloud.cmp.model.ImageModel;
import com.bocloud.cmp.model.NetworkBean;
import com.bocloud.cmp.model.NetworkModel;
import com.bocloud.cmp.model.OSSyncModel;
import com.bocloud.cmp.model.PortModel;
import com.bocloud.cmp.model.RegionModel;
import com.bocloud.cmp.model.RouteModel;
import com.bocloud.cmp.model.ServerIpModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.model.SnapshotBean;
import com.bocloud.cmp.model.SnapshotModel;
import com.bocloud.cmp.model.SubnetBean;
import com.bocloud.cmp.model.VolumeBean;
import com.bocloud.cmp.model.VolumeModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Maps;

public class SyncOSTool {
    private static Logger logger = LoggerFactory.getLogger(SyncVmwareTool.class);

    private HostSystemDao hostSystemDao;

    private NetworkDao networkDao;

    private SnapshotDao snapshotDao;

    private ImageDao imageDao;

    private FlavorDao flavorDao;

    private CloudServerDao cloudServerDao;

    private SubnetDao subnetDao;

    private RegionDao regionDao;

    private VolumeDao volumeDao;

    private PortDao portDao;

    private RouteDao routeDao;

    private ServerDao serverDao;

    private ServerIpDao serverIpDao;

    public SyncOSTool() {
        super();
    }

    public SyncOSTool(RegionDao regionDao, CloudServerDao cloudServerDao, HostSystemDao hostSystemDao,
            ServerDao serverDao, NetworkDao networkDao, SubnetDao subnetDao, VolumeDao volumeDao,
            SnapshotDao snapshotDao, ImageDao imageDao, FlavorDao flavorDao, PortDao portDao, RouteDao routeDao,
            ServerIpDao serverIpDao) {
        super();
        this.regionDao = regionDao;
        this.cloudServerDao = cloudServerDao;
        this.hostSystemDao = hostSystemDao;
        this.networkDao = networkDao;
        this.snapshotDao = snapshotDao;
        this.imageDao = imageDao;
        this.flavorDao = flavorDao;
        this.subnetDao = subnetDao;
        this.volumeDao = volumeDao;
        this.portDao = portDao;
        this.routeDao = routeDao;
        this.serverDao = serverDao;
        this.serverIpDao = serverIpDao;
    }

    public BsmResult sync(Long vendorId, Object data, Long region, Long userId) {
        try {
            if (null != data) {
                String content = JSONObject.toJSONString(data);
                List<OSSyncModel> osSyncs = JSONObject.parseArray(content, OSSyncModel.class);

                OSSyncModel osSyncModel = osSyncs.get(0);
                if (null != osSyncModel.getRegions()) {
                    this.syncaZones(osSyncModel.getRegions(), vendorId, userId);
                }
                Map<String, Long> hostIdMap = new HashMap<>();
                if (null != osSyncModel.getHostModels()) {
                    this.syncHost(osSyncModel.getHostModels(), vendorId, userId, hostIdMap);
                }
                if (null != osSyncModel.getServerModels()) {
                    List<ServerModel> serverModels = osSyncModel.getServerModels();

                    List<PortModel> portModels = osSyncModel.getPortModels();
                    updateServer(serverModels, portModels);// 增加网络关系

                    this.syncServer(osSyncModel.getServerModels(), vendorId, userId, region, hostIdMap);
                    this.syncServerIp(osSyncModel.getServerModels());
                }
                if (null != osSyncModel.getNetworkModels()) {
                    this.syncNetwork(osSyncModel.getNetworkModels(), vendorId, userId, region);
                }
                if (null != osSyncModel.getSnapshotModels()) {
                    this.syncSnapshot(osSyncModel.getSnapshotModels(), vendorId, userId, region);
                }
                if (null != osSyncModel.getVolumeModels()) {
                    this.syncVolume(osSyncModel.getVolumeModels(), vendorId, region, userId);
                }
                if (null != osSyncModel.getImageModels()) {
                    this.syncImage(osSyncModel.getImageModels(), vendorId, userId);
                }
                if (null != osSyncModel.getFlavorModels()) {
                    this.syncFlavor(osSyncModel.getFlavorModels(), vendorId, region);
                }
                if (null != osSyncModel.getPortModels()) {
                    this.syncPort(osSyncModel.getPortModels(), vendorId);
                }
                if (null != osSyncModel.getRouteModels()) {
                    this.syncRoute(osSyncModel.getRouteModels(), vendorId);
                }

            }
            return new BsmResult(true, "同步openstack平台数据成功");
        } catch (Exception e) {
            logger.error("Sync OpenStack error:{}", e);
            return new BsmResult(false, "同步openstack平台数据失败");
        }

    }

    /**
     * 关联虚拟机 和network的关系
     * 
     * @param serverModels
     * @param portModels
     */
    public void updateServer(List<ServerModel> serverModels, List<PortModel> portModels) {
        for (ServerModel serverModel : serverModels) {
            if (null != portModels) {
                for (PortModel portModel : portModels) {
                    if (serverModel.getInstanceId().equals(portModel.getDeviceId())) {
                        serverModel.setNetworkId(portModel.getNetworkId());
                    }
                }
            }
        }
    }

    /**
     * 同步可用域 available zone
     * 
     * @param regionModel
     * 
     * @param vendorId
     * 
     * @param userId
     */
    private void syncaZones(List<RegionModel> regionModels, Long vendorId, Long userId) throws Exception {

        List<Region> regions = regionDao.list(vendorId);

        Map<String, Region> mapRegion = new HashMap<String, Region>();
        for (Region region : regions) {
            mapRegion.put(region.getName(), region);
        }

        for (RegionModel regionModel : regionModels) {
            boolean flag = true;
            Region reg = new Region();

            if (mapRegion.containsKey(regionModel.getName())) { // update
                flag = false;
                reg = mapRegion.get(regionModel.getName());
                reg.setVendorId(vendorId);
                BeanUtils.copyProperties(regionModel, reg);
                regionDao.update(reg);
                mapRegion.remove(regionModel.getName());
            }
            if (flag) {
                reg.setVendorId(vendorId);
                BeanUtils.copyProperties(regionModel, reg);

                regionDao.save(reg);
                mapRegion.remove(regionModel.getName());
            }
        }
        for (String keyset : mapRegion.keySet()) {
            regionDao.delete(mapRegion.get(keyset).getId());
        }
    }

    /**
     * 物理主机和该平台下的宿主机进行同步对比
     * 
     * @param servers
     *            物理主机
     * @param hosts
     *            宿主机
     * @throws Exception
     */
    private void syncHost(List<HostModel> hostModels, Long vendorId, Long userId, Map<String, Long> hostIdMap)
            throws Exception {
        List<HostSystem> hostsystems = hostSystemDao.listByVendor(vendorId);
        List<HostSystem> resultData = new ArrayList<>();
        resultData.addAll(hostsystems);
        for (Object hostModel : hostModels) {
            boolean flag = true;
            HostModel hostmod = JSONObject.parseObject(JSONObject.toJSONString(hostModel), HostModel.class);
            for (HostSystem hostsystem : hostsystems) {
                if (hostmod.getUuid().equals(hostsystem.getUuid())) {
                    flag = false;
                    hostsystem.setMenderId(userId);
                    BeanUtils.copyProperties(hostmod, hostsystem);
                    if (hostmod.getPowerState().equals("up")) {
                        hostsystem.setPowerState(VMStatus.RUNNING.name());
                    } else if (hostmod.getPowerState().equals("down")) {
                        hostsystem.setPowerState(VMStatus.STOPPED.name());
                    }
                    if (hostmod.getStatus().equalsIgnoreCase("enabled")) {
                        hostsystem.setStatus(VMStatus.RUNNING.name());
                    } else if (hostmod.getStatus().equalsIgnoreCase("disabled")) {
                        hostsystem.setStatus(VMStatus.STOPPED.name());
                    }
                    hostSystemDao.update(hostsystem);
                    hostIdMap.put(hostsystem.getName(), hostsystem.getId());
                    resultData.remove(hostsystem);
                }
            }
            if (flag) {
                HostSystem hostsystem = JSONObject.parseObject(JSONObject.toJSONString(hostModel), HostSystem.class);
                hostsystem.setVendorId(vendorId);
                hostsystem.setCreaterId(userId);
                BeanUtils.copyProperties(hostModel, hostsystem);
                if (hostsystem.getPowerState().equals("up")) {
                    hostsystem.setPowerState(VMStatus.RUNNING.name());
                } else if (hostsystem.getPowerState().equals("down")) {
                    hostsystem.setPowerState(VMStatus.STOPPED.name());
                }
                if (hostmod.getStatus().equalsIgnoreCase("enabled")) {
                    hostsystem.setStatus(VMStatus.RUNNING.name());
                } else if (hostmod.getStatus().equalsIgnoreCase("disabled")) {
                    hostsystem.setStatus(VMStatus.STOPPED.name());
                }
                hostSystemDao.save(hostsystem);
                hostIdMap.put(hostsystem.getName(), hostsystem.getId());
            }
            for (HostSystem hostsystem : resultData) {
                hostSystemDao.remove(hostsystem.getId(), userId);
            }
            List<Server> listServer = serverDao.list(1, Integer.MAX_VALUE, null, null);
            List<HostSystem> listHost = hostSystemDao.listByVendor(vendorId);
            syncServer(listServer, listHost, userId);
        }
    }

    /**
     * 物理主机和该平台下的宿主机进行同步对比
     * 
     * @param servers
     *            物理主机
     * @param hosts
     *            宿主机
     * @throws Exception
     */
    private void syncServer(List<Server> servers, List<HostSystem> hosts, Long userId) throws Exception {
        Map<String, Server> serverMap = Maps.newHashMap();
        for (Server server : servers) {
            serverMap.put(server.getUuid() + server.getManagerIp(), server);
        }
        // 数据库不存在该uuid，则添加物理主机
        for (HostSystem host : hosts) {
            Server server = null;
            if (serverMap.containsKey(host.getUuid() + host.getHostIp())) {
                server = serverMap.get(host.getUuid() + host.getHostIp());
                String status = host.getStatus();
                if (!status.equals(server.getStatus())) {
                    server.setStatus(status);
                    server.setMenderId(userId);
                    serverDao.update(server);
                }
            } else {
                server = new Server();
                server.setName(host.getName());
                server.setUuid(host.getUuid());
                server.setManagerIp(host.getHostIp());
                server.setDiskCapacity(Integer.valueOf(host.getDiskTotal().toString()));
                server.setCpuHz(host.getCpuTotal().toString());
                server.setCreaterId(userId);
                server.setMenderId(userId);
                server.setStatus(host.getStatus());
                serverDao.save(server);
            }

        }
    }

    /**
     * 虚拟机和该平台下的虚拟机进行同步对比
     * 
     * @param servers
     *            虚拟机
     * @param hosts
     *            虚拟机
     * @throws Exception
     */
    private void syncServer(List<ServerModel> serverModels, Long vendorId, Long userId, Long region,
            Map<String, Long> hostIdMap) throws Exception {
        List<CloudServer> cloudServers = cloudServerDao.listByVendorId(vendorId);
        handlerStatus(serverModels, cloudServers, region, vendorId, userId, hostIdMap);
    }

    /**
     * 同步虚拟机Ip
     * 
     * @param serverModels
     * @throws Exception
     */
    private void syncServerIp(List<ServerModel> serverModels) throws Exception {
        for (ServerModel serverModel : serverModels) {
            List<ServerIpModel> serverIpModels = serverModel.getServerIps();
            List<ServerIp> serverIps = serverIpDao.querybyuuid(serverModel.getInstanceId());
            Map<String, ServerIp> cloudSeverIpMap = Maps.newConcurrentMap();
            if (null != serverIps) {
                for (ServerIp serverIp : serverIps) {
                    cloudSeverIpMap.put(serverIp.getAddress(), serverIp);
                }
            }
            for (ServerIpModel serverIpmodel : serverIpModels) {
                ServerIp serverIp = new ServerIp();
                if (cloudSeverIpMap.containsKey(serverIpmodel.getAddress())) {
                    serverIp = cloudSeverIpMap.get(serverIpmodel.getAddress());
                    BeanUtils.copyProperties(serverIpmodel, serverIp);
                    serverIpDao.update(serverIp);
                    cloudSeverIpMap.remove(serverIpmodel.getAddress());
                    continue;
                }
                BeanUtils.copyProperties(serverIpmodel, serverIp);
                serverIpDao.save(serverIp);
            }
            for (Entry<String, ServerIp> key : cloudSeverIpMap.entrySet()) {
                serverIpDao.remove(key.getValue().getId());
            }
        }
    }

    /**
     * 状态处理
     * 
     * @param type
     * @param data
     * @param cloudServers
     * @param region
     * @param vendorId
     */
    private boolean handlerStatus(List<ServerModel> serverModels, List<CloudServer> cloudServers, Long region,
            Long vendorId, Long userId, Map<String, Long> hostIdMap) {
        try {
            Map<String, CloudServer> cloudSeverMap = Maps.newConcurrentMap();
            for (CloudServer cloudServer : cloudServers) {
                if (null == cloudServer.getInstanceId()) {// 创建中
                    cloudServerDao.remove(CloudServer.class, cloudServer.getId());
                    continue;
                }
                if (cloudSeverMap.containsKey(cloudServer.getInstanceId())) {
                    cloudServerDao.remove(cloudServer.getId(), userId);
                } else {
                    cloudSeverMap.put(cloudServer.getInstanceId(), cloudServer);
                }
            }
            for (ServerModel server : serverModels) {
                CloudServer vm = new CloudServer();
                if (cloudSeverMap.containsKey(server.getInstanceId())) {
                    vm = cloudSeverMap.get(server.getInstanceId());
                    BeanUtils.copyProperties(server, vm);
                    vm.setStatus(server.getStatus());
                    vm.setHostId(hostIdMap.get(vm.getHostName()));
                    vm.setPassword(server.getPassword());
                    vm.setMenderId(userId);
                    vm.setIsTemplate(false);
                    cloudServerDao.update(vm);
                    cloudSeverMap.remove(vm.getInstanceId());
                    continue;
                }
                BeanUtils.copyProperties(server, vm);
                vm.setStatus(server.getStatus());
                vm.setHostId(hostIdMap.get(vm.getHostName()));
                vm.setRegion(region);
                vm.setVendorId(vendorId);
                vm.setCreaterId(userId);
                vm.setIsTemplate(false);
                cloudServerDao.save(vm);
            }

            for (Entry<String, CloudServer> key : cloudSeverMap.entrySet()) {
                cloudServerDao.remove(key.getValue().getId(), userId);
            }
            return true;
        } catch (Exception e) {
            logger.error("update cloudserver failure:", e);
            return false;
        }
    }

    /**
     * 同步虚拟机网络，包括子网
     * 
     * @param networkModels
     *            虚拟机网络
     * @param region
     *            区域
     * @throws Exception
     */
    private void syncNetwork(List<NetworkModel> networkModels, Long vendorId, Long userId, Long region)
            throws Exception {
        String status = null;
        List<Network> networks = networkDao.listByVid(vendorId);
        List<Network> resultNetwork = new ArrayList<>();
        List<Subnet> resultSubnet = new ArrayList<>();
        resultNetwork.addAll(networks);
        for (Object obj : networkModels) {
            boolean flag = true;
            NetworkBean bean = JSONObject.parseObject(JSONObject.toJSONString(obj), NetworkBean.class);
            if (bean.getStatus().equalsIgnoreCase("ACTIVE")) {
                status = VMStatus.RUNNING.name();
            } else {
                status = VMStatus.EXCEPTION.name();
            }
            for (Network network : networks) {
                if (network.getNetworkId().equals(bean.getNetworkId())) {
                    flag = false;
                    BeanUtils.copyProperties(bean, network);
                    network.setStatus(status);
                    networkDao.update(network);
                    resultNetwork.remove(network);
                }
            }
            if (flag) {
                Network network = JSONObject.parseObject(JSONObject.toJSONString(obj), Network.class);
                if (network.getStatus().equalsIgnoreCase("ACTIVE")) {
                    status = VMStatus.RUNNING.name();
                } else {
                    status = VMStatus.EXCEPTION.name();
                }
                network.setRegion(region);
                network.setVendorId(vendorId);
                network.setStatus(status);
                networkDao.save(network);
            }
            // 处理子网
            List<SubnetBean> sBeans = bean.getSubnets();
            List<Subnet> subnets = subnetDao.list(vendorId, bean.getNetworkId());
            resultSubnet.addAll(subnets);
            if (null != sBeans) {
                for (SubnetBean sBean : sBeans) {
                    flag = true;
                    for (Subnet subnet : subnets) {
                        if (subnet.getSubnetId().equals(sBean.getSubnetId())) {
                            flag = false;
                            BeanUtils.copyProperties(sBean, subnet);
                            subnetDao.modify(subnet);
                            resultSubnet.remove(subnet);
                        }
                    }
                    if (flag) {
                        Subnet subnet = new Subnet();
                        BeanUtils.copyProperties(sBean, subnet);
                        subnet.setVendorId(vendorId);
                        subnet.setRegion(region);
                        subnetDao.save(subnet);
                    }
                }
            }
        }
        // 存在异常网络数据
        for (Network net : resultNetwork) {
            // 设置虚机异常
            List<CloudServer> list = cloudServerDao.list(vendorId, net.getNetworkId());
            for (CloudServer vm : list) {
                vm.setStatus(VMStatus.EXCEPTION.name());
                cloudServerDao.update(vm);
            }
            // 删除网络
            networkDao.remove(net.getId(), userId);
        }
        // 存在异常子网数据
        for (Subnet subnet : resultSubnet) {
            subnetDao.delete(subnet.getId());
        }
    }

    /**
     * 快照同步
     * 
     * @param code
     * @param uuid
     * @param vendorId
     * @param region
     * @param userId
     * @return
     */
    private void syncSnapshot(List<SnapshotModel> snapshotModels, Long vendorId, Long userId, Long region)
            throws Exception {
        List<Snapshot> snapshots = snapshotDao.listByVid(vendorId);
        List<Snapshot> resultData = new ArrayList<>();
        resultData.addAll(snapshots);
        for (Object obj : snapshotModels) {
            boolean flag = true;
            SnapshotBean bean = JSONObject.parseObject(JSONObject.toJSONString(obj), SnapshotBean.class);
            for (Snapshot snapshot : snapshots) {
                if (snapshot.getSnapshotId().equals(bean.getSnapshotId())) {
                    flag = false;
                    BeanUtils.copyProperties(bean, snapshot);
                    snapshot.setMenderId(userId);
                    snapshotDao.update(snapshot);
                    resultData.remove(snapshot);
                }
            }
            if (flag) {
                Snapshot snapshot = JSONObject.parseObject(JSONObject.toJSONString(obj), Snapshot.class);
                snapshot.setVendorId(vendorId);
                snapshot.setRegion(region);
                snapshot.setCreaterId(userId);
                snapshotDao.save(snapshot);
            }
        }
        for (Snapshot snapshot : resultData) {
            snapshotDao.remove(snapshot.getId(), userId);
        }
    }

    /**
     * 云硬盘同步
     * 
     * @param code
     * @param uuid
     * @param vendorId
     * @param region
     * @param userId
     * @return
     * @throws Exception
     */
    private void syncVolume(List<VolumeModel> volumeModels, Long vendorId, Long region, Long userId) throws Exception {
        List<Volume> volumes = volumeDao.listByVendorId(vendorId);
        List<Volume> resultData = new ArrayList<>();
        resultData.addAll(volumes);
        for (Object obj : volumeModels) {
            boolean flag = true;
            VolumeBean bean = JSONObject.parseObject(JSONObject.toJSONString(obj), VolumeBean.class);
            for (Volume volume : volumes) {
                if (volume.getVolumeId().equals(bean.getVolumeId())) {
                    flag = false;
                    BeanUtils.copyProperties(bean, volume);
                    volume.setMenderId(userId);
                    volume.setStatus(bean.getStatus().toUpperCase());
                    volumeDao.update(volume);
                    resultData.remove(volume);
                }
            }
            if (flag) {
                Volume volume = JSONObject.parseObject(JSONObject.toJSONString(obj), Volume.class);
                if (null == volume.getName() || volume.getName().equals("")) {
                    volume.setName(volume.getVolumeId());
                }
                volume.setVendorId(vendorId);
                volume.setStatus(volume.getStatus().toUpperCase());
                volume.setRegion(region);
                volume.setCreaterId(userId);
                volumeDao.save(volume);
            }
        }
        // 删除异常数据
        for (Volume vol : resultData) {
            volumeDao.remove(vol.getId(), userId);
        }
    }

    /**
     * 镜像同步
     * 
     * @param imageModels
     * @param vendorId
     * @param region
     * @param userId
     * @return
     * @throws Exception
     */
    private void syncImage(List<ImageModel> imageModels, Long vendorId, Long userId) throws Exception {

        List<Image> images = imageDao.listByVendorId(vendorId);

        Map<String, Image> imagesMap = Maps.newConcurrentMap();
        for (Image image : images) {
            if (null == image.getImageId()) {// 创建中
                imageDao.remove(Image.class, image.getId());
                continue;
            }
            if (imagesMap.containsKey(image.getImageId())) {
                imageDao.remove(image.getId(), userId);// 如果数据库有重复，就删除掉
            } else {
                imagesMap.put(image.getImageId(), image);
            }
        }
        for (ImageModel imageModel : imageModels) {
            Image image = new Image();
            if (imagesMap.containsKey(imageModel.getImageId())) {
                image = imagesMap.get(imageModel.getImageId());
                BeanUtils.copyProperties(imageModel, image);
                image.setMenderId(userId);
                imageDao.update(image);
                imagesMap.remove(imageModel.getImageId());
                continue;
            }
            BeanUtils.copyProperties(imageModel, image);
            image.setVendorId(vendorId);
            image.setCreaterId(userId);
            imageDao.save(image);
        }
        for (Entry<String, Image> set : imagesMap.entrySet()) {
            imageDao.remove(set.getValue().getId(), userId);
        }
    }

    /**
     * 镜像同步
     * 
     * @param flavorModels
     * @param vendorId
     * @param region
     * @return
     * @throws Exception
     */
    private void syncFlavor(List<FlavorModel> flavorModels, Long vendorId, Long region) throws Exception {
        List<Flavor> flavors = flavorDao.listByVendorId(vendorId);
        List<Flavor> resultData = new ArrayList<>();
        resultData.addAll(flavors);
        for (Object obj : flavorModels) {
            boolean flag = true;
            FlavorBean bean = JSONObject.parseObject(JSONObject.toJSONString(obj), FlavorBean.class);
            for (Flavor flavor : flavors) {
                if (flavor.getFlavorId().equals(bean.getFlavorId())) {
                    flag = false;
                    BeanUtils.copyProperties(bean, flavor);
                    flavorDao.update(flavor);
                    resultData.remove(flavor);
                }
            }
            if (flag) {
                Flavor flavor = JSONObject.parseObject(JSONObject.toJSONString(obj), Flavor.class);
                flavor.setVendorId(vendorId);
                flavorDao.save(flavor);
            }
        }
        // 存在异常数据
        for (Flavor flavor : resultData) {
            // 设置虚机异常
            List<CloudServer> list = cloudServerDao.listByFid(vendorId, flavor.getFlavorId());
            for (CloudServer vm : list) {
                vm.setStatus(VMStatus.EXCEPTION.name());
                cloudServerDao.update(vm);
            }
            // 删除配置
            flavorDao.delete(flavor.getId());
        }
    }

    private void syncPort(List<PortModel> portModels, Long vendorId) throws Exception {
        List<Port> ports = portDao.listByVid(vendorId);
        Map<String, Port> portsMap = Maps.newConcurrentMap();
        for (Port port : ports) {
            if (portsMap.containsKey(port.getPortId())) {
                portDao.delete(port.getId());
            } else {
                portsMap.put(port.getPortId(), port);
            }
        }

        for (PortModel portModel : portModels) {
            Port port = new Port();
            if (portsMap.containsKey(portModel.getPortId())) {
                // update
                port = portsMap.get(portModel.getPortId());
                BeanUtils.copyProperties(portModel, port);
                port.setVendorId(vendorId);
                portDao.update(port);
                portsMap.remove(portModel.getPortId());
                continue;
            }
            BeanUtils.copyProperties(portModel, port);
            port.setVendorId(vendorId);
            portDao.save(port);
            // save
            portsMap.remove(portModel.getPortId());
        }

        for (Entry<String, Port> set : portsMap.entrySet()) {
            portDao.delete(set.getValue().getId());
        }
    }

    private void syncRoute(List<RouteModel> routeModels, Long vendorId) throws Exception {
        List<Route> routes = routeDao.listByVid(vendorId);

        Map<String, Route> routesMap = Maps.newConcurrentMap();
        for (Route route : routes) {
            if (routesMap.containsKey(route.getRouteId())) {
                routeDao.delete(route.getId());
            } else {
                routesMap.put(route.getRouteId(), route);
            }
        }

        for (RouteModel routeModel : routeModels) {
            Route route = new Route();
            if (routesMap.containsKey(routeModel.getRouteId())) {
                route = routesMap.get(routeModel.getRouteId());
                BeanUtils.copyProperties(routeModel, route);
                route.setVendorId(vendorId);
                routeDao.update(route);
                routesMap.remove(routeModel.getRouteId());
                continue;
            }
            BeanUtils.copyProperties(routeModel, route);
            route.setVendorId(vendorId);
            routeDao.save(route);
            routesMap.remove(routeModel.getRouteId());
        }
        for (Entry<String, Route> set : routesMap.entrySet()) {
            routeDao.delete(set.getValue().getId());
        }

    }
}